<?php
/**
 * Description: 每日一题方法集合
 * User: devforma
 * Date: 16/3/4
 * Time: 14:15
 */

/**
 * 获取每日一题详情
 *
 * @param $id
 * @return array
 */
function getTopicDetail($id) {
    global $cmsdb;

    $cacheKey = 'func:getTopicDetail:'.$id;
    if (!($value = cacheGet($cacheKey))) {

        //获取父文章内容及小试牛刀题目信息
        $data = $cmsdb->getRow('SELECT p.ID, p.post_date, p.post_content, p.post_title, p.post_excerpt, m.meta_value
            FROM `wp_posts` AS p INNER JOIN `wp_postmeta` AS m ON p.ID=m.post_id WHERE p.ID=:id AND p.post_type="page" AND m.meta_key="'.$id.'_postdata"',
            array(':id' => $id));
        
        if (empty($data))
            return false;

        //获取子文章内容,构造列表
        $childs = $cmsdb->getResults('SELECT `post_title`, `post_content` FROM `wp_posts` WHERE `post_parent`=:id', array(':id' => $id));

        $sections = array();
        $images = array();
        foreach ($childs as $child) {
            $title = trim(strtok($child->post_title, ' -'));
            $content = trim(htmlspecialchars($child->post_content));

            //提取内容中的图片信息
            getImageItem($images, $title, $content);

            $sections[] = array(
                'title' => $title,
                'content' => $content
            );
        }

        //构造每日一题数据结构
        $niudao = unserialize($data->meta_value);

        //小试牛刀内容和解析处理
        $content = trim(htmlspecialchars_decode($data->post_content));
        $analysis = trim(htmlspecialchars_decode($data->post_excerpt));

        getImageItem($images, "小试牛刀", $content);
        getImageItem($images, "解析", $analysis);

        $value = array(
            'id' => intval($id),
            'name' => trim(strtok($data->post_title, '-')),
            'date' => strtok($data->post_date, ' '),
            'topic' => array(
                'title' => trim($niudao['practice']),
                'content' => $content,
                'options' => array(trim($niudao['option1']), trim($niudao['option2']), trim($niudao['option3']), trim($niudao['option4'])),
                'answer' => trim(str_replace('【答案】', '', $niudao['answer'])),
                'analysis' => str_replace('【解析】', '', $analysis)
            ),
            'sections' => $sections,
            'images' => $images,
            'is_collected' => false,
            'is_done' => false,
            'user_answer' => ''
        );

        cacheAdd($cacheKey, $value, 60*60);
    }

    return $value;
}


/**
 * 获取用户行为
 *
 * @param $userId
 * @param $topicIds
 * @return array
 */

function getUserTopics($userId, $topicIds) {
    global $cmsdb;

    $userTopics = array();

    $idString = implode(',', $topicIds);
    $data = $cmsdb->getResults("SELECT * FROM `relationship_user_topic` WHERE `user_id`={$userId} AND `topic_id` IN ({$idString})");

    if (!empty($data) && is_array($data)) {
        foreach ($data as $row) {
            $userTopics[$row->topic_id] = $row;
        }
    }

    return $userTopics;
}

/**
 * 每日一题中图片处理
 *
 * @param $images
 * @param $title
 * @param $content
 * @return bool
 */
function getImageItem(&$images, $title, &$content){
    $match = explode('#', $content);
    if(empty($match))
        return false;

    $pos = 'front';
    foreach ($match as $block) {
        if (empty($block)) continue;

        if (strpos($block, 'jpg') !== false || strpos($block, 'png') !== false) {
            preg_match('_(\d+x\d+)_', $block, $size);
            $size[0] = empty($size[0]) ? '' : $size[0];
            $images[] = array(
                'filename' => 'dl/'.$block,
                'title' => $title,
                'position' => $pos,
                'size' => $size[0]
            );

        } else {
            $pos = 'end';
        }
    }

    //过滤掉内容中的图片标记
    $content = trim(preg_replace('/#[^#]+#/', '', $content));

    return true;
}


/**
 * 获取面试题目详情
 *
 * @param $questionId
 * @return bool|object
 */
function getInterviewDetail($questionId) {
    global $cmsdb;

    $cacheKey = 'func:getInterviewDetail:'.$questionId;

    if (($interview = cacheGet($cacheKey)) == null) {
        $interview = $cmsdb->getRow('SELECT * FROM `data_interview` WHERE `id`=:qid', array(':qid' => $questionId));

        if (empty($interview))
            return false;

        cacheAdd($cacheKey, $interview, 48*60*60);
    }

    return $interview;
}